package schoolTec.Prog;

import java.io.IOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;

public class Host {
	private String address;
	private int port;
	private String description;
	private int reachable = 0;	//1 == reachable; -1 == unreachable; 0 == undefined
	
	public Host(String address, int port, String description) {
		this.address = address;
		this.port = port;
		this.description = description;
	}
	
	public String getAddress() {
		return address;
	}

	public int getPort() {
		return port;
	}

	public String getDescription() {
		return description;
	}
	
	public void setReachable(int reachable) {
		this.reachable = reachable;
	}
	
	public int isReachable() {
		return this.reachable;
	}
	
	/**
	 * Ueberprueft ob ein Host auf einem Port erreichbar ist
	 * @return 1, falls erreichbar, andernfalls eine 0, bzw. -1
	 */
	public int testhost() {
		try {
			SocketAddress addr = new InetSocketAddress(InetAddress.getByName(this.address), this.port);
			Socket socket = new Socket();
			socket.connect( addr, 500 );	//timeout von 5 sekunden
			socket.close();
		}
		catch (ConnectException e){
			String ex = e.toString();
			if (ex.contains("Connection refused")) return 1;
			else return 0;
		}
		catch (UnknownHostException e) {
			return -1;
		}
		catch (IOException e) {
			return 0;
		}	
		return 1;
	}
}